package cn.wolfcode.rbac.web.exception;

import cn.wolfcode.rbac.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

//统一异常处理
@Slf4j
@RestControllerAdvice
public class CommonControllerAdvice {

    /**
     * 系统异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public R handle(Exception e) {
        e.printStackTrace();
        log.error("【系统异常】："+e.getMessage());
        return R.fail("系统异常");
    }

    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public R handleBusiness(Exception e) {
        e.printStackTrace();
        log.error("【业务异常】："+e.getMessage());
        return R.fail(e.getMessage());
    }

    /**
     * 参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        //实例化map集合：存放校验字段的错误信息
        Map<String, String> errorMap = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(fieldError -> {
            //errorFiled:errorMsg
            //错误的字段
            String errorField = fieldError.getField();
            //错误的提示消息
            String errorMsg = fieldError.getDefaultMessage();
            errorMap.put(errorField, errorMsg);
        });
        log.error("【数据校验异常】:"+errorMap);
        return R.fail(R.PARAMS_ERROR_CODE,"数据校验异常", errorMap);
    }

    /**
     * 认证异常
     * @param e
     * @return
     */
    @ExceptionHandler(BadCredentialsException.class)
    public R handlerAuthenticationException(Exception e){
        e.printStackTrace();
        log.error("【认证异常】："+e.getMessage());
        return R.fail(R.AUTHENTICATION_CODE,"用户名或密码错误");
    }

    /**
     * 授权异常
     * @param e
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public R handlerAccessDeniedException(Exception e){
        e.printStackTrace();
        log.error("【授权异常】"+e.getMessage());
        return R.fail(R.PERMISSION_CODE,e.getMessage());
    }
}
